// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Caching.Memory;
using MatrixFramework.Core.Results;
using MatrixFramework.Keycloak.Abstractions.Models;
using MatrixFramework.Keycloak.Abstractions.Options;
using MatrixFramework.Keycloak.Abstractions.Services;

namespace MatrixFramework.Keycloak.Services;

/// <summary>
/// MatrixFramework统一Keycloak管理服务实现
/// </summary>
public class KeycloakAdminService : IKeycloakAdminService
{
    private readonly ILogger<KeycloakAdminService> _logger;
    private readonly IOptionsMonitor<KeycloakOptions> _optionsMonitor;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ITenantResolver? _tenantResolver;
    private readonly Lazy<HttpClient> _httpClient;

    // Token缓存相关字段
    private volatile TokenCacheEntry? _currentToken;
    private readonly object _tokenLock = new object();
    private int _tokenExpirationSeconds = 300; // 默认5分钟过期，可动态更新

    // 性能优化相关字段
    private readonly IMemoryCache _memoryCache;
    private readonly SemaphoreSlim _semaphoreSlim;
    private readonly TimeSpan _cacheDefaultExpiration = TimeSpan.FromMinutes(5);

    public KeycloakOptions Options => _optionsMonitor.CurrentValue;

    public KeycloakAdminService(
        ILogger<KeycloakAdminService> logger,
        IOptionsMonitor<KeycloakOptions> optionsMonitor,
        IHttpClientFactory httpClientFactory,
        ITenantResolver? tenantResolver = null,
        IMemoryCache? memoryCache = null)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));
        _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
        _tenantResolver = tenantResolver;
        _httpClient = new Lazy<HttpClient>(CreateHttpClient);

        // 性能优化组件初始化
        _memoryCache = memoryCache ?? new MemoryCache(new MemoryCacheOptions());
        _semaphoreSlim = new SemaphoreSlim(Environment.ProcessorCount, Environment.ProcessorCount * 2);
    }

    private HttpClient CreateHttpClient()
    {
        var client = _httpClientFactory.CreateClient("KeycloakAdmin");
        var options = Options;

        // 配置基础URL
        client.BaseAddress = new Uri(options.BaseUrl);

        // 设置默认请求头
        client.DefaultRequestHeaders.Add("User-Agent", options.HttpClient.UserAgent);

        // 配置超时
        client.Timeout = TimeSpan.FromSeconds(options.TimeoutSeconds);

        return client;
    }

    private async Task<string> GetEffectiveRealmAsync(string? realmName = null)
    {
        if (!string.IsNullOrWhiteSpace(realmName))
            return realmName;

        if (!Options.MultiTenant.Enabled)
            return Options.DefaultRealm;

        var tenantId = await _tenantResolver.ResolveTenantAsync();
        if (!string.IsNullOrWhiteSpace(tenantId))
        {
            // 根据租户ID生成Realm名称
            return Options.MultiTenant.RealmNaming switch
            {
                RealmNamingStrategy.TenantId => tenantId,
                RealmNamingStrategy.CustomPrefix => $"{Options.MultiTenant.TenantPrefix}{tenantId}",
                _ => Options.MultiTenant.DefaultRealmTemplate.Replace("{tenant-id}", tenantId, StringComparison.OrdinalIgnoreCase)
            };
        }

        return Options.DefaultRealm;
    }

    private async Task<HttpClient> GetAuthenticatedClientAsync()
    {
        var client = _httpClient.Value;

        // 获取访问令牌
        var token = await GetAccessTokenAsync();
        if (string.IsNullOrEmpty(token))
        {
            throw new InvalidOperationException("无法获取Keycloak访问令牌");
        }

        // 设置Authorization头
        if (client.DefaultRequestHeaders.Contains("Authorization"))
        {
            client.DefaultRequestHeaders.Remove("Authorization");
        }
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

        return client;
    }

    private async Task<string> GetAccessTokenAsync()
    {
        lock (_tokenLock)
        {
            // 双重检查锁定模式
            if (_currentToken != null && !IsTokenExpired(_currentToken))
            {
                return _currentToken.AccessToken;
            }
        }

        // 在锁外获取新Token以避免阻塞
        var newToken = await RequestAccessTokenAsync();

        lock (_tokenLock)
        {
            // 再次检查，防止并发获取Token
            if (_currentToken == null || IsTokenExpired(_currentToken))
            {
                _currentToken = new TokenCacheEntry
                {
                    AccessToken = newToken,
                    ExpiresAt = DateTime.UtcNow.AddSeconds(_tokenExpirationSeconds - Options.TokenExpirationBufferMinutes * 60)
                };

                _logger.LogDebug("获取到新的Keycloak访问令牌，过期时间: {ExpiresAt}", _currentToken.ExpiresAt);
            }

            return _currentToken.AccessToken;
        }
    }

    private async Task<string> RequestAccessTokenAsync()
    {
        var client = _httpClientFactory.CreateClient();
        var options = Options;

        var tokenEndpoint = $"{options.BaseUrl}/realms/master/protocol/openid-connect/token";

        var parameters = new Dictionary<string, string>
        {
            ["grant_type"] = "password",
            ["client_id"] = options.AdminClientId,
            ["client_secret"] = options.AdminClientSecret,
            ["username"] = options.AdminUsername,
            ["password"] = options.AdminPassword
        };

        using var content = new FormUrlEncodedContent(parameters);

        try
        {
            var response = await client.PostAsync(tokenEndpoint, content).ConfigureAwait(false);
            response.EnsureSuccessStatusCode();

            var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            var tokenResponse = JsonSerializer.Deserialize<TokenResponse>(responseContent);

            if (tokenResponse?.AccessToken == null)
            {
                throw new InvalidOperationException("Keycloak返回了无效的令牌响应");
            }

            // 更新Token过期时间
            if (tokenResponse.ExpiresIn > 0)
            {
                _tokenExpirationSeconds = tokenResponse.ExpiresIn;
            }

            return tokenResponse.AccessToken;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取Keycloak访问令牌失败");
            throw;
        }
    }

    // ==================== Realm管理 ====================

    public async Task<Result<RealmCreationResult>> CreateRealmAsync(RealmCreationInfo realmInfo, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(realmInfo);

        try
        {
            var client = await GetAuthenticatedClientAsync();
            var adminEndpoint = $"/admin/realms";

            var keycloakRealm = new
            {
                realm = realmInfo.RealmName,
                displayName = realmInfo.DisplayName,
                description = realmInfo.Description,
                enabled = realmInfo.Enabled,
                attributes = realmInfo.Attributes
            };

            var content = JsonContent.Create(keycloakRealm);
            var response = await client.PostAsync(adminEndpoint, content, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var result = new RealmCreationResult
                {
                    RealmName = realmInfo.RealmName,
                    RealmId = realmInfo.RealmName,
                    CreatedAt = DateTime.UtcNow,
                    AdminConsoleUrl = $"{Options.BaseUrl}/admin/master/console/#/realms/{realmInfo.RealmName}"
                };

                // 创建管理员用户（如果提供）
                if (realmInfo.AdminUser != null)
                {
                    var adminUserResult = await CreateUserInRealmAsync(realmInfo.AdminUser, realmInfo.RealmName, cancellationToken);
                    if (adminUserResult.IsSuccess)
                    {
                        result.AdminUsername = realmInfo.AdminUser.Username;
                        result.AdminPassword = realmInfo.AdminUser.Password;
                    }
                }

                _logger.LogInformation("成功创建Realm: {RealmName}", realmInfo.RealmName);
                return Result<RealmCreationResult>.Success(result);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("创建Realm失败: {StatusCode} - {Content}", response.StatusCode, errorContent);
                return Result<RealmCreationResult>.Failure($"创建Realm失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "创建Realm时网络请求失败: {RealmName}", realmInfo.RealmName);
            return Result<RealmCreationResult>.Failure($"网络请求失败: {ex.Message}");
        }
        catch (TaskCanceledException ex)
        {
            _logger.LogError(ex, "创建Realm时请求超时: {RealmName}", realmInfo.RealmName);
            return Result<RealmCreationResult>.Failure("请求超时，请稍后重试");
        }
        catch (JsonException ex)
        {
            _logger.LogError(ex, "创建Realm时JSON解析失败: {RealmName}", realmInfo.RealmName);
            return Result<RealmCreationResult>.Failure("响应数据格式错误");
        }
        catch (OperationCanceledException)
        {
            _logger.LogWarning("创建Realm操作被取消: {RealmName}", realmInfo.RealmName);
            return Result<RealmCreationResult>.Failure("操作被取消");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建Realm时发生未知异常: {RealmName}", realmInfo.RealmName);
            return Result<RealmCreationResult>.Failure($"创建Realm失败: {ex.Message}");
        }
    }

    public async Task<Result> DeleteRealmAsync(string realmName, CancellationToken cancellationToken = default)
    {
        try
        {
            var client = await GetAuthenticatedClientAsync();
            var adminEndpoint = $"/admin/realms/{realmName}";

            var response = await client.DeleteAsync(adminEndpoint, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("成功删除Realm: {RealmName}", realmName);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("删除Realm失败: {StatusCode} - {Content}", response.StatusCode, errorContent);
                return Result.Failure($"删除Realm失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "删除Realm时网络请求失败: {RealmName}", realmName);
            return Result.Failure($"网络请求失败: {ex.Message}");
        }
        catch (TaskCanceledException ex)
        {
            _logger.LogError(ex, "删除Realm时请求超时: {RealmName}", realmName);
            return Result.Failure("请求超时，请稍后重试");
        }
        catch (OperationCanceledException)
        {
            _logger.LogWarning("删除Realm操作被取消: {RealmName}", realmName);
            return Result.Failure("操作被取消");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除Realm时发生未知异常: {RealmName}", realmName);
            return Result.Failure($"删除Realm失败: {ex.Message}");
        }
    }

    public async Task<Result<RealmInfo>> GetRealmAsync(string realmName, CancellationToken cancellationToken = default)
    {
        try
        {
            var client = await GetAuthenticatedClientAsync();
            var adminEndpoint = $"/admin/realms/{realmName}";

            var response = await client.GetAsync(adminEndpoint, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync(cancellationToken);
                var realmData = JsonSerializer.Deserialize<Dictionary<string, object>>(content);

                if (realmData == null)
                {
                    return Result<RealmInfo>.Failure("无法解析Realm数据");
                }

                var realmInfo = new RealmInfo
                {
                    Realm = realmName,
                    DisplayName = realmData.GetValueOrDefault("displayName")?.ToString(),
                    Enabled = bool.Parse(realmData.GetValueOrDefault("enabled")?.ToString() ?? "false"),
                    Description = realmData.GetValueOrDefault("description")?.ToString(),
                    Attributes = ExtractAttributes(realmData.GetValueOrDefault("attributes"))
                };

                _logger.LogDebug("成功获取Realm信息: {RealmName}", realmName);
                return Result<RealmInfo>.Success(realmInfo);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("获取Realm信息失败: {StatusCode} - {Content}", response.StatusCode, errorContent);
                return Result<RealmInfo>.Failure($"获取Realm信息失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "获取Realm信息时网络请求失败: {RealmName}", realmName);
            return Result<RealmInfo>.Failure($"网络请求失败: {ex.Message}");
        }
        catch (TaskCanceledException ex)
        {
            _logger.LogError(ex, "获取Realm信息时请求超时: {RealmName}", realmName);
            return Result<RealmInfo>.Failure("请求超时，请稍后重试");
        }
        catch (OperationCanceledException)
        {
            _logger.LogWarning("获取Realm信息操作被取消: {RealmName}", realmName);
            return Result<RealmInfo>.Failure("操作被取消");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取Realm信息时发生未知异常: {RealmName}", realmName);
            return Result<RealmInfo>.Failure($"获取Realm信息失败: {ex.Message}");
        }
    }

    public async Task<Result> UpdateRealmAsync(string realmName, RealmConfiguration configuration, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(configuration);

        try
        {
            var client = await GetAuthenticatedClientAsync();
            var adminEndpoint = $"/admin/realms/{realmName}";

            var updateData = new Dictionary<string, object>();

            if (configuration.DisplayName != null)
                updateData["displayName"] = configuration.DisplayName;

            if (configuration.Description != null)
                updateData["description"] = configuration.Description;

            if (configuration.Enabled.HasValue)
                updateData["enabled"] = configuration.Enabled.Value;

            if (configuration.Attributes != null)
                updateData["attributes"] = configuration.Attributes;

            var content = JsonContent.Create(updateData);
            var response = await client.PutAsync(adminEndpoint, content, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("成功更新Realm配置: {RealmName}", realmName);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("更新Realm配置失败: {StatusCode} - {Content}", response.StatusCode, errorContent);
                return Result.Failure($"更新Realm配置失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新Realm配置时发生异常: {RealmName}", realmName);
            return Result.Failure(ex.Message);
        }
    }

    public async Task<Result<bool>> TestRealmConnectionAsync(string realmName, CancellationToken cancellationToken = default)
    {
        try
        {
            var result = await GetRealmAsync(realmName, cancellationToken);
            return Result<bool>.Success(result.IsSuccess);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "测试Realm连接时发生异常: {RealmName}", realmName);
            return Result<bool>.Failure(ex.Message);
        }
    }

    // ==================== 用户管理 ====================

    public async Task<Result<UserCreationResult>> CreateUserAsync(UserCreationInfo userInfo, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            return await CreateUserInRealmAsync(userInfo, effectiveRealm, cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建用户时发生异常: {Username}", userInfo.Username);
            return Result<UserCreationResult>.Failure(ex.Message);
        }
    }

    private async Task<Result<UserCreationResult>> CreateUserInRealmAsync(UserCreationInfo userInfo, string realmName, CancellationToken cancellationToken)
    {
        var client = await GetAuthenticatedClientAsync();
        var adminEndpoint = $"/admin/realms/{realmName}/users";

        var keycloakUser = new
        {
            username = userInfo.Username,
            email = userInfo.Email,
            firstName = userInfo.FirstName,
            lastName = userInfo.LastName,
            enabled = userInfo.Enabled,
            emailVerified = userInfo.EmailVerified,
            credentials = new[]
            {
                new
                {
                    type = "password",
                    value = userInfo.Password,
                    temporary = false
                }
            },
            attributes = userInfo.Attributes
        };

        var content = JsonContent.Create(keycloakUser);
        var response = await client.PostAsync(adminEndpoint, content, cancellationToken);

        if (response.IsSuccessStatusCode)
        {
            // 获取Location头来提取用户ID
            var locationHeader = response.Headers.Location?.ToString();
            var userId = ExtractUserIdFromLocation(locationHeader);

            // 分配角色
            if (userInfo.Roles.Count > 0)
            {
                await AssignRolesToUserInRealmAsync(userId, userInfo.Roles, realmName, cancellationToken);
            }

            var result = new UserCreationResult
            {
                UserId = userId,
                Username = userInfo.Username,
                CreatedAt = DateTime.UtcNow,
                TemporaryPassword = userInfo.Password
            };

            _logger.LogInformation("成功创建用户: {Username} in realm {Realm}", userInfo.Username, realmName);
            return Result<UserCreationResult>.Success(result);
        }
        else
        {
            var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
            _logger.LogError("创建用户失败: {StatusCode} - {Content}", response.StatusCode, errorContent);
            return Result<UserCreationResult>.Failure($"创建用户失败: {response.StatusCode}");
        }
    }

    // 辅助方法

    private Dictionary<string, object> ExtractAttributes(object? attributesData)
    {
        var attributes = new Dictionary<string, object>();

        if (attributesData is JsonElement jsonElement && jsonElement.ValueKind == JsonValueKind.Object)
        {
            foreach (var property in jsonElement.EnumerateObject())
            {
                attributes[property.Name] = property.Value;
            }
        }

        return attributes;
    }

    private string ExtractUserIdFromLocation(string? location)
    {
        if (string.IsNullOrEmpty(location))
            return Guid.NewGuid().ToString();

        var segments = location.Split('/');
        var userIdSegment = segments.LastOrDefault();

        return Guid.TryParse(userIdSegment, out var userId) ? userId.ToString() : userIdSegment ?? Guid.NewGuid().ToString();
    }

    // 简化的用户角色分配方法
    private async Task AssignRolesToUserInRealmAsync(string userId, List<string> roleNames, string realmName, CancellationToken cancellationToken)
    {
        if (roleNames.Count == 0) return;

        var client = await GetAuthenticatedClientAsync();
        var adminEndpoint = $"/admin/realms/{realmName}/users/{userId}/role-mappings/realm";

        var rolesData = roleNames.Select(roleName => new { name = roleName }).ToArray();
        var content = JsonContent.Create(rolesData);

        await client.PostAsync(adminEndpoint, content, cancellationToken);
    }

    // 其他方法的简化实现（占位符）
    public async Task<Result> UpdateUserAsync(string userId, UserUpdateInfo userInfo, string? realmName = null, CancellationToken cancellationToken = default)
    {
        var realm = realmName ?? Options.DefaultRealm;
        var adminEndpoint = $"{Options.BaseUrl}/admin/realms/{realm}/users/{userId}";

        try
        {
            // 构建用户更新数据
            var updateData = new Dictionary<string, object>();

            if (!string.IsNullOrEmpty(userInfo.Email))
                updateData["email"] = userInfo.Email;

            if (!string.IsNullOrEmpty(userInfo.FirstName))
                updateData["firstName"] = userInfo.FirstName;

            if (!string.IsNullOrEmpty(userInfo.LastName))
                updateData["lastName"] = userInfo.LastName;

            if (userInfo.Enabled.HasValue)
                updateData["enabled"] = userInfo.Enabled.Value;

            if (userInfo.Attributes != null)
                updateData["attributes"] = userInfo.Attributes;

            // 发送更新请求
            var content = JsonContent.Create(updateData);
            var response = await _httpClient.Value.PutAsync(adminEndpoint, content, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("用户 {UserId} 更新成功", userId);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("更新用户失败: {StatusCode} - {Error}", response.StatusCode, errorContent);
                return Result.Failure($"更新用户失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "更新用户时发生网络错误");
            return Result.Failure($"网络错误: {ex.Message}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新用户时发生未知错误");
            return Result.Failure($"未知错误: {ex.Message}");
        }
    }

    public async Task<Result> DeleteUserAsync(string userId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        var realm = realmName ?? Options.DefaultRealm;
        var adminEndpoint = $"{Options.BaseUrl}/admin/realms/{realm}/users/{userId}";

        try
        {
            var response = await _httpClient.Value.DeleteAsync(adminEndpoint, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("用户 {UserId} 删除成功", userId);
                return Result.Success();
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                _logger.LogWarning("用户 {UserId} 不存在", userId);
                return Result.Success(); // 用户不存在也算删除成功
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("删除用户失败: {StatusCode} - {Error}", response.StatusCode, errorContent);
                return Result.Failure($"删除用户失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "删除用户时发生网络错误");
            return Result.Failure($"网络错误: {ex.Message}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除用户时发生未知错误");
            return Result.Failure($"未知错误: {ex.Message}");
        }
    }

    public async Task<Result<UserInfo>> GetUserAsync(string userId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        var realm = realmName ?? Options.DefaultRealm;
        var adminEndpoint = $"{Options.BaseUrl}/admin/realms/{realm}/users/{userId}";

        try
        {
            var response = await _httpClient.Value.GetAsync(adminEndpoint, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var userJson = await response.Content.ReadAsStringAsync(cancellationToken);
                var user = JsonSerializer.Deserialize<KeycloakUserRepresentation>(userJson, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (user != null)
                {
                    var userInfo = MapToUserInfo(user);
                    _logger.LogInformation("获取用户 {UserId} 信息成功", userId);
                    return Result<UserInfo>.Success(userInfo);
                }
                else
                {
                    return Result<UserInfo>.Failure("用户数据解析失败");
                }
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return Result<UserInfo>.Failure("用户不存在");
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("获取用户信息失败: {StatusCode} - {Error}", response.StatusCode, errorContent);
                return Result<UserInfo>.Failure($"获取用户信息失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "获取用户信息时发生网络错误");
            return Result<UserInfo>.Failure($"网络错误: {ex.Message}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户信息时发生未知错误");
            return Result<UserInfo>.Failure($"未知错误: {ex.Message}");
        }
    }

    public async Task<Result<UserInfo?>> GetUserByUsernameAsync(string username, string? realmName = null, CancellationToken cancellationToken = default)
    {
        var realm = realmName ?? Options.DefaultRealm;
        var adminEndpoint = $"{Options.BaseUrl}/admin/realms/{realm}/users?username={Uri.EscapeDataString(username)}&exact=true";

        try
        {
            var response = await _httpClient.Value.GetAsync(adminEndpoint, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var usersJson = await response.Content.ReadAsStringAsync(cancellationToken);
                var users = JsonSerializer.Deserialize<List<KeycloakUserRepresentation>>(usersJson, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (users != null && users.Count > 0)
                {
                    var user = users.First();
                    var userInfo = MapToUserInfo(user);
                    _logger.LogInformation("根据用户名 {Username} 获取用户信息成功", username);
                    return Result<UserInfo?>.Success(userInfo);
                }
                else
                {
                    return Result<UserInfo?>.Success(null);
                }
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("根据用户名获取用户信息失败: {StatusCode} - {Error}", response.StatusCode, errorContent);
                return Result<UserInfo?>.Failure($"根据用户名获取用户信息失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "根据用户名获取用户信息时发生网络错误");
            return Result<UserInfo?>.Failure($"网络错误: {ex.Message}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据用户名获取用户信息时发生未知错误");
            return Result<UserInfo?>.Failure($"未知错误: {ex.Message}");
        }
    }

    public async Task<Result<PagedSearchResult<UserInfo>>> SearchUsersAsync(UserSearchRequest searchRequest, string? realmName = null, CancellationToken cancellationToken = default)
    {
        // TODO: 实现用户搜索逻辑
        await Task.Delay(1, cancellationToken);
        return Result<PagedSearchResult<UserInfo>>.Failure("暂未实现");
    }

    public async Task<Result> ResetPasswordAsync(string userId, string newPassword, string? realmName = null, CancellationToken cancellationToken = default)
    {
        var realm = realmName ?? Options.DefaultRealm;
        var adminEndpoint = $"{Options.BaseUrl}/admin/realms/{realm}/users/{userId}/reset-password";

        try
        {
            var passwordData = new
            {
                type = "password",
                value = newPassword,
                temporary = false // 不是临时密码
            };

            var content = JsonContent.Create(passwordData);
            var response = await _httpClient.Value.PutAsync(adminEndpoint, content, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("用户 {UserId} 密码重置成功", userId);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("重置用户密码失败: {StatusCode} - {Error}", response.StatusCode, errorContent);
                return Result.Failure($"重置用户密码失败: {response.StatusCode}");
            }
        }
        catch (HttpRequestException ex)
        {
            _logger.LogError(ex, "重置用户密码时发生网络错误");
            return Result.Failure($"网络错误: {ex.Message}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "重置用户密码时发生未知错误");
            return Result.Failure($"未知错误: {ex.Message}");
        }
    }

    // 角色管理相关方法（占位符）
    public async Task<Result<RoleCreationResult>> CreateRoleAsync(RoleCreationInfo roleInfo, string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<RoleCreationResult>.Failure("暂未实现");
    }

    public async Task<Result> DeleteRoleAsync(string roleName, string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result.Success();
    }

    public async Task<Result<List<RoleInfo>>> GetRolesAsync(string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<List<RoleInfo>>.Success(new List<RoleInfo>());
    }

    public async Task<Result> AssignRolesToUserAsync(string userId, List<string> roleNames, string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result.Success();
    }

    public async Task<Result> RemoveRolesFromUserAsync(string userId, List<string> roleNames, string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result.Success();
    }

    
    // 客户端管理相关方法（占位符）
    public async Task<Result<ClientCreationResult>> CreateClientAsync(ClientCreationInfo clientInfo, string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<ClientCreationResult>.Failure("暂未实现");
    }

    public async Task<Result<ClientInfo>> GetClientAsync(string clientId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<ClientInfo>.Failure("暂未实现");
    }

    public async Task<Result<List<ClientInfo>>> GetClientsAsync(string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<List<ClientInfo>>.Success(new List<ClientInfo>());
    }

    // 权限作用域管理相关方法（占位符）
    public async Task<Result<ScopeCreationResult>> CreateScopeAsync(ScopeCreationInfo scopeInfo, string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<ScopeCreationResult>.Failure("暂未实现");
    }

    public async Task<Result<List<ScopeInfo>>> GetScopesAsync(string? realmName = null, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<List<ScopeInfo>>.Success(new List<ScopeInfo>());
    }

    // 多租户管理相关方法（占位符）
    public async Task<Result<TenantSyncResult>> SyncTenantAsync(TenantInfo tenantInfo, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<TenantSyncResult>.Failure("暂未实现");
    }

    public async Task<Result<BatchTenantSyncResult>> SyncTenantsAsync(List<TenantInfo> tenantInfos, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<BatchTenantSyncResult>.Failure("暂未实现");
    }

    public async Task<Result<TenantSyncStatus>> GetTenantSyncStatusAsync(string tenantId, CancellationToken cancellationToken = default)
    {
        await Task.Delay(1, cancellationToken);
        return Result<TenantSyncStatus>.Failure("暂未实现");
    }

    // 健康检查相关方法（占位符）
    public async Task<Result<bool>> TestConnectionAsync(CancellationToken cancellationToken = default)
    {
        try
        {
            var client = _httpClient.Value;
            var response = await client.GetAsync("/auth/realms/master", cancellationToken);
            return Result<bool>.Success(response.IsSuccessStatusCode);
        }
        catch (Exception ex)
        {
            return Result<bool>.Failure(ex.Message);
        }
    }

    public async Task<Result<ServerInfo>> GetServerInfoAsync(CancellationToken cancellationToken = default)
    {
        _logger.LogDebug("开始获取Keycloak服务器信息");

        var client = _httpClient.Value;
        var serverInfoEndpoint = $"{Options.BaseUrl}/realms/master/.well-known/openid-configuration";

        var stopwatch = System.Diagnostics.Stopwatch.StartNew();

        try
        {
            // 首先尝试从OpenID配置获取信息
            var response = await client.GetAsync(serverInfoEndpoint, cancellationToken);
            stopwatch.Stop();

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync(cancellationToken);
                var openIdConfig = JsonSerializer.Deserialize<OpenIdConfiguration>(content, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (openIdConfig?.Issuer != null)
                {
                    var serverInfo = new ServerInfo
                    {
                        Version = ExtractVersionFromIssuer(openIdConfig.Issuer),
                        Configuration = new Dictionary<string, object>
                        {
                            ["Issuer"] = openIdConfig.Issuer,
                            ["AuthorizationEndpoint"] = openIdConfig.AuthorizationEndpoint,
                            ["TokenEndpoint"] = openIdConfig.TokenEndpoint,
                            ["UserInfoEndpoint"] = openIdConfig.UserInfoEndpoint,
                            ["EndSessionEndpoint"] = openIdConfig.EndSessionEndpoint,
                            ["CheckSessionIframe"] = openIdConfig.CheckSessionIframe,
                            ["JwksUri"] = openIdConfig.JwksUri,
                            ["BaseUrl"] = Options.BaseUrl,
                            ["ResponseTimeMs"] = stopwatch.ElapsedMilliseconds,
                            ["CheckTime"] = DateTime.UtcNow,
                            ["ConnectionStatus"] = "Connected"
                        }
                    };

                    // 尝试获取更多服务器信息
                    await EnrichServerInfoAsync(serverInfo, client, cancellationToken);

                    _logger.LogInformation("成功获取Keycloak服务器信息，响应时间: {ResponseTimeMs}ms", stopwatch.ElapsedMilliseconds);
                    return Result<ServerInfo>.Success(serverInfo);
                }
            }
            else
            {
                _logger.LogWarning("获取OpenID配置失败，状态码: {StatusCode}", response.StatusCode);
            }
        }
        catch (HttpRequestException httpEx)
        {
            stopwatch.Stop();
            _logger.LogError(httpEx, "获取Keycloak服务器信息HTTP异常，响应时间: {ResponseTimeMs}ms", stopwatch.ElapsedMilliseconds);
            return Result<ServerInfo>.Failure($"HTTP请求失败: {httpEx.Message}");
        }
        catch (TaskCanceledException)
        {
            stopwatch.Stop();
            _logger.LogWarning("获取Keycloak服务器信息被取消");
            return Result<ServerInfo>.Failure("请求被取消");
        }
        catch (Exception ex)
        {
            stopwatch.Stop();
            _logger.LogError(ex, "获取Keycloak服务器信息异常，响应时间: {ResponseTimeMs}ms", stopwatch.ElapsedMilliseconds);
            return Result<ServerInfo>.Failure($"服务器信息获取失败: {ex.Message}");
        }

        // 如果OpenID配置失败，尝试通过服务器信息API获取
        try
        {
            return await GetServerInfoFromAdminApi(client, cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "从Admin API获取服务器信息失败");
            return Result<ServerInfo>.Failure($"所有获取服务器信息的方法都失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 执行额外的健康检查
    /// </summary>
    /// <param name="checks">健康检查项目字典</param>
    /// <param name="client">HTTP客户端</param>
    /// <param name="cancellationToken">取消令牌</param>
    private async Task PerformAdditionalHealthChecks(Dictionary<string, HealthCheckItem> checks, HttpClient client, CancellationToken cancellationToken = default)
    {
        var tasks = new List<Task>
        {
            CheckTokenEndpointAsync(checks, client, cancellationToken),
            CheckJwksEndpointAsync(checks, client, cancellationToken),
            CheckAdminEndpointAsync(checks, client, cancellationToken),
            CheckPerformanceAsync(checks, client, cancellationToken)
        };

        // 并行执行所有健康检查
        await Task.WhenAll(tasks);
    }

    /// <summary>
    /// 检查Token端点
    /// </summary>
    private async Task CheckTokenEndpointAsync(Dictionary<string, HealthCheckItem> checks, HttpClient client, CancellationToken cancellationToken)
    {
        try
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var tokenEndpoint = $"{Options.BaseUrl}/realms/master/protocol/openid-connect/token";

            // 发送OPTIONS请求检查端点可用性
            var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Options, tokenEndpoint), cancellationToken);
            stopwatch.Stop();

            checks["TokenEndpoint"] = new HealthCheckItem
            {
                Name = "Token端点检查",
                Passed = response.StatusCode >= System.Net.HttpStatusCode.OK && response.StatusCode < System.Net.HttpStatusCode.BadRequest,
                ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                Message = $"Token端点响应状态: {response.StatusCode}",
                Details = new Dictionary<string, object>
                {
                    ["Endpoint"] = tokenEndpoint,
                    ["StatusCode"] = (int)response.StatusCode
                }
            };
        }
        catch (Exception ex)
        {
            checks["TokenEndpoint"] = new HealthCheckItem
            {
                Name = "Token端点检查",
                Passed = false,
                ResponseTimeMs = 0,
                Message = $"Token端点检查失败: {ex.Message}",
                Details = new Dictionary<string, object>
                {
                    ["ExceptionType"] = ex.GetType().Name
                }
            };
        }
    }

    /// <summary>
    /// 检查JWKS端点
    /// </summary>
    private async Task CheckJwksEndpointAsync(Dictionary<string, HealthCheckItem> checks, HttpClient client, CancellationToken cancellationToken)
    {
        try
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var jwksEndpoint = $"{Options.BaseUrl}/realms/master/protocol/openid-connect/certs";

            var response = await client.GetAsync(jwksEndpoint, cancellationToken);
            stopwatch.Stop();

            var passed = response.IsSuccessStatusCode;
            string message = passed ? "JWKS端点正常" : $"JWKS端点响应异常: {response.StatusCode}";

            if (passed)
            {
                // 验证响应内容是否为有效的JSON
                var content = await response.Content.ReadAsStringAsync(cancellationToken);
                JsonDocument.Parse(content); // 验证JSON格式
                message = "JWKS端点正常，内容有效";
            }

            checks["JwksEndpoint"] = new HealthCheckItem
            {
                Name = "JWKS端点检查",
                Passed = passed,
                ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                Message = message,
                Details = new Dictionary<string, object>
                {
                    ["Endpoint"] = jwksEndpoint,
                    ["StatusCode"] = (int)response.StatusCode
                }
            };
        }
        catch (JsonException ex)
        {
            checks["JwksEndpoint"] = new HealthCheckItem
            {
                Name = "JWKS端点检查",
                Passed = false,
                ResponseTimeMs = 0,
                Message = $"JWKS端点响应内容无效: {ex.Message}",
                Details = new Dictionary<string, object>
                {
                    ["ExceptionType"] = ex.GetType().Name
                }
            };
        }
        catch (Exception ex)
        {
            checks["JwksEndpoint"] = new HealthCheckItem
            {
                Name = "JWKS端点检查",
                Passed = false,
                ResponseTimeMs = 0,
                Message = $"JWKS端点检查失败: {ex.Message}",
                Details = new Dictionary<string, object>
                {
                    ["ExceptionType"] = ex.GetType().Name
                }
            };
        }
    }

    /// <summary>
    /// 检查管理端点
    /// </summary>
    private async Task CheckAdminEndpointAsync(Dictionary<string, HealthCheckItem> checks, HttpClient client, CancellationToken cancellationToken)
    {
        try
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            var adminEndpoint = $"{Options.BaseUrl}/admin/realms";

            // 不需要认证，只需要检查端点是否存在
            var response = await client.GetAsync(adminEndpoint, cancellationToken);
            stopwatch.Stop();

            // 401或403表示端点存在但需要认证，这也算是健康的
            var passed = response.StatusCode == System.Net.HttpStatusCode.Unauthorized ||
                      response.StatusCode == System.Net.HttpStatusCode.Forbidden ||
                      response.IsSuccessStatusCode;

            checks["AdminEndpoint"] = new HealthCheckItem
            {
                Name = "管理端点检查",
                Passed = passed,
                ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                Message = $"管理端点响应状态: {response.StatusCode}",
                Details = new Dictionary<string, object>
                {
                    ["Endpoint"] = adminEndpoint,
                    ["StatusCode"] = (int)response.StatusCode,
                    ["RequiresAuth"] = response.StatusCode == System.Net.HttpStatusCode.Unauthorized ||
                                     response.StatusCode == System.Net.HttpStatusCode.Forbidden
                }
            };
        }
        catch (Exception ex)
        {
            checks["AdminEndpoint"] = new HealthCheckItem
            {
                Name = "管理端点检查",
                Passed = false,
                ResponseTimeMs = 0,
                Message = $"管理端点检查失败: {ex.Message}",
                Details = new Dictionary<string, object>
                {
                    ["ExceptionType"] = ex.GetType().Name
                }
            };
        }
    }

    /// <summary>
    /// 检查性能指标
    /// </summary>
    private async Task CheckPerformanceAsync(Dictionary<string, HealthCheckItem> checks, HttpClient client, CancellationToken cancellationToken)
    {
        try
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            // 执行多次请求检查平均响应时间
            var testEndpoint = $"{Options.BaseUrl}/realms/master/.well-known/openid-configuration";
            var responseTimes = new List<long>();

            for (int i = 0; i < 3; i++)
            {
                var requestStopwatch = System.Diagnostics.Stopwatch.StartNew();
                var response = await client.GetAsync(testEndpoint, cancellationToken);
                requestStopwatch.Stop();

                responseTimes.Add(requestStopwatch.ElapsedMilliseconds);

                if (!response.IsSuccessStatusCode)
                {
                    break; // 如果请求失败，停止后续测试
                }
            }

            stopwatch.Stop();

            var averageResponseTime = responseTimes.Count > 0
                ? (long)responseTimes.Average()
                : 0;

            var passed = averageResponseTime > 0 && averageResponseTime < 5000; // 5秒以内算正常

            checks["Performance"] = new HealthCheckItem
            {
                Name = "性能检查",
                Passed = passed,
                ResponseTimeMs = averageResponseTime,
                Message = passed
                    ? $"平均响应时间: {averageResponseTime}ms"
                    : $"响应时间过长: {averageResponseTime}ms",
                Details = new Dictionary<string, object>
                {
                    ["AverageResponseTime"] = averageResponseTime,
                    ["RequestCount"] = responseTimes.Count,
                    ["ResponseTimes"] = responseTimes
                }
            };
        }
        catch (Exception ex)
        {
            checks["Performance"] = new HealthCheckItem
            {
                Name = "性能检查",
                Passed = false,
                ResponseTimeMs = 0,
                Message = $"性能检查失败: {ex.Message}",
                Details = new Dictionary<string, object>
                {
                    ["ExceptionType"] = ex.GetType().Name
                }
            };
        }
    }

    /// <summary>
    /// 丰富服务器信息
    /// </summary>
    /// <param name="serverInfo">服务器信息对象</param>
    /// <param name="client">HTTP客户端</param>
    /// <param name="cancellationToken">取消令牌</param>
    private async Task EnrichServerInfoAsync(ServerInfo serverInfo, HttpClient client, CancellationToken cancellationToken = default)
    {
        try
        {
            // 尝试获取服务器状态信息
            await GetServerStatusAsync(serverInfo, client, cancellationToken);

            // 尝试获取服务器指标信息
            await GetServerMetricsAsync(serverInfo, client, cancellationToken);

            // 添加功能列表
            AddServerFeatures(serverInfo);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "丰富服务器信息时发生异常，将使用基本信息");
        }
    }

    /// <summary>
    /// 获取服务器状态信息
    /// </summary>
    private async Task GetServerStatusAsync(ServerInfo serverInfo, HttpClient client, CancellationToken cancellationToken)
    {
        try
        {
            // 尝试访问Keycloak管理端点获取状态
            var statusEndpoint = $"{Options.BaseUrl}/admin/serverinfo";
            var response = await client.GetAsync(statusEndpoint, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync(cancellationToken);
                var statusData = JsonSerializer.Deserialize<JsonElement>(content);

                if (statusData.ValueKind == JsonValueKind.Object)
                {
                    serverInfo.SystemInfo = new MatrixFramework.Keycloak.Abstractions.Models.SystemInfo();

                    if (statusData.TryGetProperty("systemInfo", out var systemInfoElement))
                    {
                        ExtractSystemInfo(systemInfoElement, serverInfo.SystemInfo);
                    }

                    if (statusData.TryGetProperty("memory", out var memoryElement))
                    {
                        serverInfo.MemoryInfo = ExtractMemoryInfo(memoryElement);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogDebug(ex, "获取服务器状态信息失败，可能是权限或端点问题");
        }
    }

    /// <summary>
    /// 获取服务器指标信息
    /// </summary>
    private async Task GetServerMetricsAsync(ServerInfo serverInfo, HttpClient client, CancellationToken cancellationToken)
    {
        try
        {
            // 尝试获取服务器指标
            var metricsEndpoint = $"{Options.BaseUrl}/realms/master/.well-known/openid-configuration";
            var response = await client.GetAsync(metricsEndpoint, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                // 添加指标相关信息到配置中
                serverInfo.Configuration["MetricsEndpoint"] = $"{Options.BaseUrl}/realms/master/metrics";
                serverInfo.Configuration["HealthEndpoint"] = $"{Options.BaseUrl}/health";

                // 添加服务器能力信息
                serverInfo.Configuration["SupportsOpenID"] = true;
                serverInfo.Configuration["SupportsOAuth2"] = true;
                serverInfo.Configuration["SupportsMFA"] = true; // Keycloak通常支持MFA
            }
        }
        catch (Exception ex)
        {
            _logger.LogDebug(ex, "获取服务器指标信息失败");
        }
    }

    /// <summary>
    /// 添加服务器功能列表
    /// </summary>
    private void AddServerFeatures(ServerInfo serverInfo)
    {
        var features = new List<string>
        {
            "OpenID Connect",
            "OAuth 2.0",
            "JSON Web Tokens (JWT)",
            "Multi-Factor Authentication (MFA)",
            "Single Sign-On (SSO)",
            "Role-Based Access Control (RBAC)",
            "User Federation",
            "Social Login Integration",
            "Account Management",
            "Password Policies",
            "Session Management",
            "Security Headers",
            "CORS Support"
        };

        serverInfo.Features = features;
    }

    /// <summary>
    /// 从JSON元素提取系统信息
    /// </summary>
    private void ExtractSystemInfo(JsonElement systemInfoElement, MatrixFramework.Keycloak.Abstractions.Models.SystemInfo systemInfo)
    {
        if (systemInfoElement.TryGetProperty("javaVersion", out var javaVersion))
            systemInfo.JavaVersion = javaVersion.GetString();

        if (systemInfoElement.TryGetProperty("javaVendor", out var javaVendor))
            systemInfo.JavaVendor = javaVendor.GetString();

        if (systemInfoElement.TryGetProperty("osName", out var osName))
            systemInfo.OsName = osName.GetString();

        if (systemInfoElement.TryGetProperty("osVersion", out var osVersion))
            systemInfo.OsVersion = osVersion.GetString();

        if (systemInfoElement.TryGetProperty("osArchitecture", out var osArchitecture))
            systemInfo.OsArchitecture = osArchitecture.GetString();

        if (systemInfoElement.TryGetProperty("hostname", out var hostname))
            systemInfo.HostName = hostname.GetString();
    }

    /// <summary>
    /// 提取内存信息
    /// </summary>
    private MemoryInfo ExtractMemoryInfo(JsonElement memoryElement)
    {
        var memoryInfo = new MemoryInfo();

        if (memoryElement.TryGetProperty("totalMemory", out var totalMemory))
            memoryInfo.TotalMemory = totalMemory.GetInt64();

        if (memoryElement.TryGetProperty("freeMemory", out var freeMemory))
            memoryInfo.FreeMemory = freeMemory.GetInt64();

        if (memoryElement.TryGetProperty("maxMemory", out var maxMemory))
            memoryInfo.MaxMemory = maxMemory.GetInt64();

        return memoryInfo;
    }

    /// <summary>
    /// 从Issuer URL提取版本信息
    /// </summary>
    private static string ExtractVersionFromIssuer(string? issuer)
    {
        if (string.IsNullOrWhiteSpace(issuer))
            return "Unknown";

        // 尝试从URL路径中提取版本
        var segments = issuer.Split('/');
        for (int i = 0; i < segments.Length - 1; i++)
        {
            if (segments[i].Equals("realms", StringComparison.OrdinalIgnoreCase))
            {
                return segments[i + 1];
            }
        }

        return "Unknown";
    }

    /// <summary>
    /// 从管理API获取服务器信息
    /// </summary>
    private async Task<Result<ServerInfo>> GetServerInfoFromAdminApi(HttpClient client, CancellationToken cancellationToken)
    {
        try
        {
            // 获取认证客户端
            var authClient = await GetAuthenticatedClientAsync();
            var adminInfoEndpoint = $"{Options.BaseUrl}/admin/serverinfo";

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            var response = await authClient.GetAsync(adminInfoEndpoint, cancellationToken);
            stopwatch.Stop();

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync(cancellationToken);
                var adminInfo = JsonSerializer.Deserialize<KeycloakAdminInfo>(content, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                if (adminInfo != null)
                {
                    var serverInfo = new ServerInfo
                    {
                        Version = adminInfo.SystemInfo?.Version ?? "Unknown",
                        Configuration = new Dictionary<string, object>
                        {
                            ["Realm"] = adminInfo.Realm ?? "master",
                            ["AdminInfo"] = adminInfo,
                            ["ResponseTimeMs"] = stopwatch.ElapsedMilliseconds,
                            ["CheckTime"] = DateTime.UtcNow
                        }
                    };

                    _logger.LogInformation("成功从管理API获取Keycloak服务器信息");
                    return Result<ServerInfo>.Success(serverInfo);
                }
                else
                {
                    return Result<ServerInfo>.Failure("管理API返回的数据格式无效");
                }
            }
            else
            {
                _logger.LogWarning("从管理API获取服务器信息失败，状态码: {StatusCode}", response.StatusCode);
                return Result<ServerInfo>.Failure($"管理API请求失败，状态码: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "从管理API获取服务器信息异常");
            return Result<ServerInfo>.Failure($"管理API请求异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 健康检查
    /// </summary>
    public async Task<Result<HealthCheckResult>> HealthCheckAsync(CancellationToken cancellationToken = default)
    {
        var startTime = DateTime.UtcNow;

        try
        {
            _logger.LogDebug("开始Keycloak健康检查");

            // 测试基本连接
            var client = _httpClient.Value;
            var healthEndpoint = $"{Options.BaseUrl}/health";

            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            try
            {
                // 尝试获取服务器信息
                var serverInfoResult = await GetServerInfoAsync(cancellationToken);
                stopwatch.Stop();

                if (serverInfoResult.IsSuccess)
                {
                    var serverInfo = serverInfoResult.Data;
                    var checks = new Dictionary<string, HealthCheckItem>
                    {
                        ["ServerInfo"] = new HealthCheckItem
                        {
                            Name = "服务器信息检查",
                            Passed = true,
                            ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                            Message = "成功获取服务器信息"
                        },
                        ["Connection"] = new HealthCheckItem
                        {
                            Name = "连接检查",
                            Passed = true,
                            ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                            Message = $"成功连接到 {Options.BaseUrl}"
                        }
                    };

                    // 执行额外的健康检查
                    await PerformAdditionalHealthChecks(checks, client, cancellationToken);

                    var healthCheckResult = new HealthCheckResult
                    {
                        IsHealthy = checks.Values.All(c => c.Passed),
                        CheckTime = startTime,
                        ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                        ServerVersion = serverInfo?.Version,
                        ServerInfo = serverInfo,
                        Checks = checks
                    };

                    var status = healthCheckResult.IsHealthy ? "通过" : "失败";
                    _logger.LogInformation("Keycloak健康检查{Status}，响应时间: {ResponseTimeMs}ms，检查项: {CheckCount}",
                        status, healthCheckResult.ResponseTimeMs, checks.Count);

                    return Result<HealthCheckResult>.Success(healthCheckResult);
                }
                else
                {
                    // 服务器信息获取失败，但基本连接可能正常
                    stopwatch.Stop();

                    var healthCheckResult = new HealthCheckResult
                    {
                        IsHealthy = false,
                        CheckTime = startTime,
                        ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                        Checks = new Dictionary<string, HealthCheckItem>
                        {
                            ["ServerInfo"] = new HealthCheckItem
                            {
                                Name = "服务器信息检查",
                                Passed = false,
                                ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                                Message = serverInfoResult.IsSuccess ? "获取服务器信息失败" : "服务器信息获取失败"
                            },
                            ["Connection"] = new HealthCheckItem
                            {
                                Name = "连接检查",
                                Passed = true,
                                ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                                Message = $"成功连接到 {Options.BaseUrl}"
                            }
                        }
                    };

                    _logger.LogWarning("Keycloak健康检查失败: 服务器信息获取失败");

                    return Result<HealthCheckResult>.Success(healthCheckResult);
                }
            }
            catch (Exception ex)
            {
                stopwatch.Stop();

                var healthCheckResult = new HealthCheckResult
                {
                    IsHealthy = false,
                    CheckTime = startTime,
                    ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                    Checks = new Dictionary<string, HealthCheckItem>
                    {
                        ["Connection"] = new HealthCheckItem
                        {
                            Name = "连接检查",
                            Passed = false,
                            ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                            Message = $"连接失败: {ex.Message}",
                            Details = new Dictionary<string, object>
                            {
                                ["ExceptionType"] = ex.GetType().Name
                            }
                        },
                        ["ServerInfo"] = new HealthCheckItem
                        {
                            Name = "服务器信息检查",
                            Passed = false,
                            ResponseTimeMs = stopwatch.ElapsedMilliseconds,
                            Message = "无法获取服务器信息",
                            Details = new Dictionary<string, object>
                            {
                                ["ExceptionType"] = ex.GetType().Name
                            }
                        }
                    }
                };

                _logger.LogError(ex, "Keycloak健康检查异常，响应时间: {ResponseTimeMs}ms",
                    healthCheckResult.ResponseTimeMs);

                return Result<HealthCheckResult>.Success(healthCheckResult);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "健康检查过程中发生异常");
            return Result<HealthCheckResult>.Failure($"健康检查异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 将Keycloak用户表示映射为UserInfo
    /// </summary>
    private static UserInfo MapToUserInfo(KeycloakUserRepresentation user)
    {
        return new UserInfo
        {
            Id = user.Id,
            Username = user.Username,
            Email = user.Email,
            FirstName = user.FirstName,
            LastName = user.LastName,
            EmailVerified = user.EmailVerified,
            Enabled = user.Enabled,
            Roles = user.Roles ?? new List<string>(),
            Groups = user.Groups ?? new List<string>(),
            Attributes = user.Attributes ?? new Dictionary<string, object>(),
            CreatedTimestamp = user.CreatedTimestamp ?? DateTime.UtcNow
        };
    }

    /// <summary>
    /// 检查Token是否过期
    /// </summary>
    /// <param name="tokenEntry">Token缓存条目</param>
    /// <returns>是否过期</returns>
    private static bool IsTokenExpired(TokenCacheEntry tokenEntry)
    {
        // 提前30秒过期以确保安全
        return DateTime.UtcNow.AddSeconds(30) >= tokenEntry.ExpiresAt;
    }

    // ==================== 缺失的接口实现方法 ====================

    /// <summary>
    /// 获取用户列表（搜索用户的别名方法）
    /// </summary>
    public async Task<Result<PagedSearchResult<UserInfo>>> GetUsersAsync(UserSearchRequest searchRequest, string? realmName = null, CancellationToken cancellationToken = default)
    {
        return await SearchUsersAsync(searchRequest, realmName, cancellationToken);
    }

    /// <summary>
    /// 启用/禁用用户
    /// </summary>
    public async Task<Result> SetUserEnabledAsync(string userId, bool enabled, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var updateData = new { enabled = enabled };
            var response = await client.PutAsJsonAsync($"/admin/realms/{effectiveRealm}/users/{userId}", updateData, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("成功{Action}用户: {UserId}", enabled ? "启用" : "禁用", userId);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("设置用户状态失败: {Error}", errorContent);
                return Result.Failure($"设置用户状态失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "设置用户状态异常: {UserId}, Enabled: {Enabled}", userId, enabled);
            return Result.Failure($"设置用户状态异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取用户角色
    /// </summary>
    public async Task<Result<List<string>>> GetUserRolesAsync(string userId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var response = await client.GetAsync($"/admin/realms/{effectiveRealm}/users/{userId}/role-mappings/realm", cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var roles = await response.Content.ReadFromJsonAsync<List<KeycloakRoleRepresentation>>(cancellationToken: cancellationToken);
                var roleNames = roles?.Select(r => r.Name).ToList() ?? new List<string>();

                _logger.LogDebug("获取用户角色成功: {UserId}, 角色数量: {Count}", userId, roleNames.Count);
                return Result<List<string>>.Success(roleNames);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("获取用户角色失败: {Error}", errorContent);
                return Result<List<string>>.Failure($"获取用户角色失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户角色异常: {UserId}", userId);
            return Result<List<string>>.Failure($"获取用户角色异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取用户组
    /// </summary>
    public async Task<Result<List<string>>> GetUserGroupsAsync(string userId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var response = await client.GetAsync($"/admin/realms/{effectiveRealm}/users/{userId}/groups", cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var groups = await response.Content.ReadFromJsonAsync<List<KeycloakGroupRepresentation>>(cancellationToken: cancellationToken);
                var groupNames = groups?.Select(g => g.Name).ToList() ?? new List<string>();

                _logger.LogDebug("获取用户组成功: {UserId}, 组数量: {Count}", userId, groupNames.Count);
                return Result<List<string>>.Success(groupNames);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("获取用户组失败: {Error}", errorContent);
                return Result<List<string>>.Failure($"获取用户组失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户组异常: {UserId}", userId);
            return Result<List<string>>.Failure($"获取用户组异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 将用户添加到组
    /// </summary>
    public async Task<Result> AddUserToGroupAsync(string userId, string groupId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var response = await client.PutAsync($"/admin/realms/{effectiveRealm}/users/{userId}/groups/{groupId}", null, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("成功将用户添加到组: {UserId}, GroupId: {GroupId}", userId, groupId);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("将用户添加到组失败: {Error}", errorContent);
                return Result.Failure($"将用户添加到组失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "将用户添加到组异常: {UserId}, GroupId: {GroupId}", userId, groupId);
            return Result.Failure($"将用户添加到组异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 将用户从组中移除
    /// </summary>
    public async Task<Result> RemoveUserFromGroupAsync(string userId, string groupId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var response = await client.DeleteAsync($"/admin/realms/{effectiveRealm}/users/{userId}/groups/{groupId}", cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("成功将用户从组中移除: {UserId}, GroupId: {GroupId}", userId, groupId);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("将用户从组中移除失败: {Error}", errorContent);
                return Result.Failure($"将用户从组中移除失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "将用户从组中移除异常: {UserId}, GroupId: {GroupId}", userId, groupId);
            return Result.Failure($"将用户从组中移除异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取用户会话列表
    /// </summary>
    public async Task<Result<List<UserSessionInfo>>> GetUserSessionsAsync(string userId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var response = await client.GetAsync($"/admin/realms/{effectiveRealm}/users/{userId}/sessions", cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var sessions = await response.Content.ReadFromJsonAsync<List<KeycloakSessionRepresentation>>(cancellationToken: cancellationToken);
                var sessionInfos = sessions?.Select(s => new UserSessionInfo
                {
                    Id = s.Id,
                    UserId = userId,
                    Username = s.Username ?? string.Empty,
                    ClientId = s.ClientId ?? string.Empty,
                    IpAddress = s.IpAddress,
                    StartedAt = s.Start ?? DateTime.UtcNow,
                    LastAccessAt = s.LastAccess ?? DateTime.UtcNow,
                    ExpiresAt = s.Expires,
                    IsActive = true,
                    UserAgent = s.UserAgent
                }).ToList() ?? new List<UserSessionInfo>();

                _logger.LogDebug("获取用户会话成功: {UserId}, 会话数量: {Count}", userId, sessionInfos.Count);
                return Result<List<UserSessionInfo>>.Success(sessionInfos);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("获取用户会话失败: {Error}", errorContent);
                return Result<List<UserSessionInfo>>.Failure($"获取用户会话失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户会话异常: {UserId}", userId);
            return Result<List<UserSessionInfo>>.Failure($"获取用户会话异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 注销用户所有会话
    /// </summary>
    public async Task<Result> LogoutUserAsync(string userId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var response = await client.PostAsync($"/admin/realms/{effectiveRealm}/users/{userId}/logout", null, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("成功注销用户会话: {UserId}", userId);
                return Result.Success();
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("注销用户会话失败: {Error}", errorContent);
                return Result.Failure($"注销用户会话失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "注销用户会话异常: {UserId}", userId);
            return Result.Failure($"注销用户会话异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 验证用户凭据
    /// </summary>
    public async Task<Result<bool>> ValidateUserCredentialsAsync(string username, string password, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = _httpClientFactory.CreateClient("KeycloakAdmin");
            client.BaseAddress = new Uri(Options.BaseUrl);

            var tokenRequest = new Dictionary<string, string>
            {
                ["grant_type"] = "password",
                ["client_id"] = Options.AdminClientId,
                ["username"] = username,
                ["password"] = password
            };

            // 如果是保密客户端，添加client_secret
            if (!string.IsNullOrEmpty(Options.AdminClientSecret))
            {
                tokenRequest["client_secret"] = Options.AdminClientSecret;
            }

            var content = new FormUrlEncodedContent(tokenRequest);
            var response = await client.PostAsync($"/realms/{effectiveRealm}/protocol/openid-connect/token", content, cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                _logger.LogDebug("用户凭据验证成功: {Username}", username);
                return Result<bool>.Success(true);
            }
            else
            {
                _logger.LogDebug("用户凭据验证失败: {Username}", username);
                return Result<bool>.Success(false);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证用户凭据异常: {Username}", username);
            return Result<bool>.Failure($"验证用户凭据异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取用户权限
    /// </summary>
    public async Task<Result<List<string>>> GetUserPermissionsAsync(string userId, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var response = await client.GetAsync($"/admin/realms/{effectiveRealm}/users/{userId}/permissions", cancellationToken);

            if (response.IsSuccessStatusCode)
            {
                var permissions = await response.Content.ReadFromJsonAsync<List<string>>(cancellationToken: cancellationToken);
                var permissionList = permissions ?? new List<string>();

                _logger.LogDebug("获取用户权限成功: {UserId}, 权限数量: {Count}", userId, permissionList.Count);
                return Result<List<string>>.Success(permissionList);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                _logger.LogError("获取用户权限失败: {Error}", errorContent);
                return Result<List<string>>.Failure($"获取用户权限失败: {response.StatusCode}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户权限异常: {UserId}", userId);
            return Result<List<string>>.Failure($"获取用户权限异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 批量导入用户
    /// </summary>
    public async Task<Result<UserImportResult>> ImportUsersAsync(List<UserCreationInfo> users, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            if (users == null || !users.Any())
            {
                return Result<UserImportResult>.Failure("用户列表不能为空");
            }

            var effectiveRealm = await GetEffectiveRealmAsync(realmName);
            var client = await GetAuthenticatedClientAsync();

            var batchId = Guid.NewGuid();
            var successItems = new List<UserImportSuccessItem>();
            var errorItems = new List<UserImportErrorItem>();

            foreach (var user in users)
            {
                try
                {
                    var userRepresentation = new
                    {
                        username = user.Username,
                        email = user.Email,
                        firstName = user.FirstName,
                        lastName = user.LastName,
                        enabled = user.Enabled,
                        emailVerified = user.EmailVerified,
                        credentials = new[]
                        {
                            new { type = "password", value = user.Password, temporary = false }
                        }
                    };

                    var response = await client.PostAsJsonAsync($"/admin/realms/{effectiveRealm}/users", userRepresentation, cancellationToken);

                    if (response.IsSuccessStatusCode)
                    {
                        var location = response.Headers.Location?.ToString();
                        var userId = location?.Split('/').LastOrDefault();

                        if (!string.IsNullOrEmpty(userId))
                        {
                            successItems.Add(new UserImportSuccessItem
                            {
                                Username = user.Username,
                                UserId = userId,
                                Email = user.Email
                            });
                        }
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
                        errorItems.Add(new UserImportErrorItem
                        {
                            Username = user.Username,
                            ErrorMessage = errorContent,
                            ErrorCode = response.StatusCode.ToString()
                        });
                    }
                }
                catch (Exception ex)
                {
                    errorItems.Add(new UserImportErrorItem
                    {
                        Username = user.Username,
                        ErrorMessage = ex.Message,
                        ErrorCode = "EXCEPTION"
                    });
                }
            }

            var result = new UserImportResult
            {
                BatchId = batchId,
                TotalUsers = users.Count,
                SuccessCount = successItems.Count,
                FailedCount = errorItems.Count,
                SkippedCount = 0,
                SuccessItems = successItems,
                ErrorItems = errorItems,
                ImportedAt = DateTime.UtcNow
            };

            _logger.LogInformation("批量导入用户完成: 总数={TotalUsers}, 成功={SuccessCount}, 失败={FailedCount}",
                result.TotalUsers, result.SuccessCount, result.FailedCount);

            return Result<UserImportResult>.Success(result);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "批量导入用户异常");
            return Result<UserImportResult>.Failure($"批量导入用户异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 导出用户
    /// </summary>
    public async Task<Result<UserExportResult>> ExportUsersAsync(UserSearchRequest searchRequest, string? realmName = null, CancellationToken cancellationToken = default)
    {
        try
        {
            var searchResult = await SearchUsersAsync(searchRequest, realmName, cancellationToken);
            if (!searchResult.IsSuccess)
            {
                return Result<UserExportResult>.Failure($"搜索用户失败: {searchResult.Error}");
            }

            var exportResult = new UserExportResult
            {
                SearchRequest = searchRequest,
                TotalUsers = searchResult.Data.TotalCount,
                ExportedUsers = searchResult.Data.Items.Count,
                Format = ExportFormat.Json,
                FilePath = $"/tmp/users_export_{Guid.NewGuid()}.json",
                FileSizeBytes = 0,
                ExportedAt = DateTime.UtcNow,
                DownloadUrl = null,
                ExpiresAt = DateTime.UtcNow.AddHours(24)
            };

            // 在实际实现中，这里会生成实际的文件
            _logger.LogInformation("用户导出完成: 总数={TotalUsers}, 导出={ExportedUsers}",
                exportResult.TotalUsers, exportResult.ExportedUsers);

            return Result<UserExportResult>.Success(exportResult);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "导出用户异常");
            return Result<UserExportResult>.Failure($"导出用户异常: {ex.Message}");
        }
    }
}

// 辅助类
internal class TokenResponse
{
    public string AccessToken { get; set; } = string.Empty;
    public string TokenType { get; set; } = string.Empty;
    public int ExpiresIn { get; set; }
    public string RefreshToken { get; set; } = string.Empty;
}

/// <summary>
/// Token缓存条目
/// </summary>
internal class TokenCacheEntry
{
    /// <summary>
    /// 访问令牌
    /// </summary>
    public string AccessToken { get; set; } = string.Empty;

    /// <summary>
    /// 过期时间
    /// </summary>
    public DateTime ExpiresAt { get; set; }
}

/// <summary>
/// OpenID配置信息
/// </summary>
internal class OpenIdConfiguration
{
    public string? Issuer { get; set; }
    public string? AuthorizationEndpoint { get; set; }
    public string? TokenEndpoint { get; set; }
    public string? UserInfoEndpoint { get; set; }
    public string? EndSessionEndpoint { get; set; }
    public string? CheckSessionIframe { get; set; }
    public string? JwksUri { get; set; }
    public string[]? GrantTypesSupported { get; set; }
    public string[]? ResponseTypesSupported { get; set; }
    public string[]? SubjectTypesSupported { get; set; }
    public string[]? IdTokenSigningAlgValuesSupported { get; set; }
    public string[]? ScopesSupported { get; set; }
}

/// <summary>
/// Keycloak管理API信息
/// </summary>
internal class KeycloakAdminInfo
{
    public string? Realm { get; set; }
    public SystemInfo? SystemInfo { get; set; }
    public Dictionary<string, object>? MemoryInfo { get; set; }
    public Dictionary<string, object>? Themes { get; set; }
}

/// <summary>
/// Keycloak系统信息
/// </summary>
internal class SystemInfo
{
    public string? Version { get; set; }
    public string? ServerTime { get; set; }
    public string? Uptime { get; set; }
    public Dictionary<string, object>? Environment { get; set; }
}

// 临时类，需要从Microsoft.AspNetCore.Http添加
public class HttpContextAccessor : IHttpContextAccessor
{
    public HttpContext? HttpContext { get; set; }
}

public interface IHttpContextAccessor
{
    HttpContext? HttpContext { get; set; }
}

public class HttpContext
{
    public HttpRequest Request { get; set; } = new();
    public Dictionary<string, object> Items { get; set; } = new();
}

public class HttpRequest
{
    public Dictionary<string, string> Headers { get; set; } = new();
    public Dictionary<string, string> Query { get; set; } = new();
}

/// <summary>
/// Keycloak用户表示类
/// </summary>
internal class KeycloakUserRepresentation
{
    public string Id { get; set; } = string.Empty;
    public string Username { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public bool Enabled { get; set; }
    public bool EmailVerified { get; set; }
    public List<string> Roles { get; set; } = new();
    public List<string> Groups { get; set; } = new();
    public Dictionary<string, object> Attributes { get; set; } = new();
    public DateTime? CreatedTimestamp { get; set; }
}

/// <summary>
/// Keycloak角色表示类
/// </summary>
internal class KeycloakRoleRepresentation
{
    public string Id { get; set; } = string.Empty;
    public string Name { get; set; } = string.Empty;
    public string? Description { get; set; }
}

/// <summary>
/// Keycloak组表示类
/// </summary>
internal class KeycloakGroupRepresentation
{
    public string Id { get; set; } = string.Empty;
    public string Name { get; set; } = string.Empty;
    public string? Path { get; set; }
}

/// <summary>
/// Keycloak会话表示类
/// </summary>
internal class KeycloakSessionRepresentation
{
    public string Id { get; set; } = string.Empty;
    public string? Username { get; set; }
    public string? ClientId { get; set; }
    public string? IpAddress { get; set; }
    public DateTime? Start { get; set; }
    public DateTime? LastAccess { get; set; }
    public DateTime? Expires { get; set; }
    public string? UserAgent { get; set; }
}
